package com.zh.risk.base;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.zh.common.entity.JSONResult;
import com.zh.common.entity.SystemLog;
import com.zh.common.util.CheckObjAllFieldsIsNullUtil;
import com.zh.common.util.IpAddressUtil;
import com.zh.risk.aop.GetRequestParams;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @version 1.0
 * @Description : service层日志记录
 * @Author : chenfei
 * @Create in : 2020/11/11 17:05
 */
@Aspect
@Component
public class BaseServiceAop {

    @Autowired
    private MongoTemplate mongoTemplate;

    private static final Logger logger = LoggerFactory.getLogger(BaseServiceAop.class);

    private Long date = null;

    @Pointcut("@within( org.springframework.stereotype.Service) && !@annotation(com.zh.common.aop.SpecialAop)")
    public void serviceAopLog() { }


    @Async
    @Before(value = "serviceAopLog()")
    public void BeforeMod(@NotNull JoinPoint jp) {
        //设置请求时间
        date  = new Date().getTime();
    }

    @AfterReturning(returning = "value",pointcut = "serviceAopLog()")
    public void afterAop(JoinPoint joinPoint,Object value) {
        SystemLog systemLog = new SystemLog();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(Objects.nonNull(requestAttributes)){
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            String ip = IpAddressUtil.getIpAddress(request);
            systemLog.setIp(ip);
            systemLog.setPath(request.getRequestURI());
            //获取请求的参数
            Enumeration<String> enumeration = request.getParameterNames();
            Map<String,String> parameterMap = Maps.newHashMap();
            while (enumeration.hasMoreElements()){
                String parameter = enumeration.nextElement();
                parameterMap.put(parameter,request.getParameter(parameter));
            }
            systemLog.setRequest(JSON.toJSONString(parameterMap));
        }
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        systemLog.setMethod(method.getName());
        systemLog.setNotes(method.getName());
        //systemLog.setRequest(JSON.toJSONString(joinPoint.getArgs()));获取请求参数
        systemLog.setResponse(JSON.toJSONString(value));
        systemLog.setLogType(1);
        systemLog.setServiceName("ZH-CLOUD-RISK-SERVICE");
        Long resultDate =new Date().getTime();
        systemLog.setTime((resultDate-date) +"ms" );
        systemLog.setCreateDate(DateUtil.now());
        mongoTemplate.insert(systemLog);
    }



}
